package com.mrdeer.web.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mrdeer.common.constants.CommonConstant;
import com.mrdeer.common.entity.dto.UserRoleDTO;
import com.mrdeer.common.entity.sys.Role;
import com.mrdeer.common.entity.sys.User;
import com.mrdeer.common.entity.sys.UserRole;
import com.mrdeer.web.mapper.SysUserMapper;
import com.mrdeer.web.mapper.UserRoleMapper;
import com.mrdeer.web.service.sys.SysUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@Transactional
public class SysUserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements SysUserRoleService {

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public UserRole add(UserRole userRole) {
        return null;
    }

    @Override
    public boolean delete(String id) {
        return false;
    }

    @Override
    public UserRole update(UserRole userRole) {
        return null;
    }

    @Override
    public UserRole getById(String id) {
        return null;
    }

    @Override
    public Page<UserRole> list(UserRoleDTO dto) {
        return null;
    }

    @Override
    public LambdaQueryWrapper<UserRole> fuzzyQuery(UserRoleDTO dto) {
        return null;
    }

    @Override
    public List<Role> findByUserId(String userId) {
        return userRoleMapper.findByUserId(userId);
    }

    @Override
    public List<String> findDepIdsByUserId(String userId) {
        return userRoleMapper.findDepIdsByUserId(userId);
    }

    @Override
    public List<UserRole> findByRoleId(String roleId) {
        return userRoleMapper.selectList(new LambdaQueryWrapper<UserRole>().eq(UserRole::getRoleId, roleId));
    }

    @Override
    public List<User> findUserByRoleId(String roleId) {
        List<UserRole> userRoleList = userRoleMapper.selectList(new QueryWrapper<UserRole>().eq("role_id", roleId));
        List<User> list = new ArrayList<>();
        for (UserRole ur : userRoleList) {
            User u = sysUserMapper.selectById(ur.getUserId());
            if (u != null && CommonConstant.USER_STATUS_NORMAL.equals(u.getStatus())) {
                list.add(u);
            }
        }
        return list;
    }

    @Override
    public void deleteByUserId(String userId) {
        userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id", userId));
    }
}
